package com.bootdo.app.controller;

import com.bootdo.common.utils.MD5Utils;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.UuidUtils;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/app/")
public class AppLoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private CacheManager cacheManager;

    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public R login(String username, String password) {
        //获取MD5加密的密码
        password = MD5Utils.encrypt(username, password);
        //获取token(随机生成token值)
        String token = UuidUtils.getUUID();
        //根据用户名，密码获取用户信息
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("username",username);
        map.put("password",password);
        UserDO userDO = userService.getUserDetail(map);
        if(null == userDO) {
            return R.error("用户或密码错误");
        }
        //更新到ehcache缓存中
        Cache cache = cacheManager.getCache("user");
        cache.put(token,userDO);
        map.put("token",token);
        return R.ok(map);
    }

}
